package com.sunyard.authorization.controller;

import com.sunyard.authorization.bean.FetchToken;
import com.sunyard.authorization.bean.RefreshBO;
import com.sunyard.authorization.config.CustomizedToken;
import com.sunyard.authorization.service.ManageOperatorService;
import com.sunyard.authorization.service.TokenService;
import com.sunyard.constant.CommonConst;
import com.sunyard.response.Response;
import com.sunyard.dal.entity.Operator;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/auth")
public class TokenController {
    Logger logger = LoggerFactory.getLogger(TokenController.class);
    @Autowired
    TokenService tokenService;
    @Autowired
    ManageOperatorService manageOperatorService;

    @PostMapping("/fetchToken")
    public Object fetchManageToken(@RequestBody FetchToken fetchToken) {
        try {
            logger.info("fetchToken params:{}", fetchToken.toString());
            Subject currentUser = SecurityUtils.getSubject();
            CustomizedToken customizedToken = new CustomizedToken(
                    fetchToken.getUsername(),
                    fetchToken.getPassword(),
                    fetchToken.getApplicationId());
            logger.info("获取currentUser:{}",currentUser);
            if (!currentUser.isAuthenticated()) {
                currentUser.login(customizedToken);
                Operator loginOperator = manageOperatorService.getOperatorByOpNameString(fetchToken.getUsername());
                logger.info("生成token前参数:{}",loginOperator);
                return Response.success(generateManageToken(loginOperator));
            }
            return CommonConst.getResult(CommonConst.RET_FAIL, "账号已登陆");
        } catch (Exception e) {
            logger.error("获取权限异常", e);
            return CommonConst.getResult(CommonConst.RET_FAIL, "获取权限异常");
        }
    }

    @PostMapping("/fetchMerchantToken")
    public Object fetchMerchantToken(@RequestBody FetchToken fetchToken) {
        logger.info("fetchMerchantToken params:{}", fetchToken.toString());
        Subject currentUser = SecurityUtils.getSubject();
        CustomizedToken customizedToken = new CustomizedToken(
                fetchToken.getUsername(),
                fetchToken.getPassword(),
                fetchToken.getApplicationId());
        if (!currentUser.isAuthenticated()) {
            currentUser.login(customizedToken);
            return Response.success(generateMerchantToken(fetchToken.getUsername()));
        }
        return CommonConst.getResult(CommonConst.RET_FAIL, "账号已登陆");
    }

    private String generateManageToken(Operator operator) {
        return tokenService.fetchManageToken(
                operator.getOpId(),
                operator.getOpName(),
                operator.getOrgId(),
                operator.getRoleId(),
                operator.getOrgLevel(),
                operator.getAuditType());
    }

    private String generateMerchantToken(String loginName) {
        return tokenService.fetchMerchantToken(loginName);
    }

    @PostMapping("/refreshToken")
    public Object refreshToken(@RequestBody RefreshBO refreshBO) {
        try {
            return tokenService.refreshToken(refreshBO.getToken());
        } catch (Exception e) {
            logger.error("刷新权限失败：", e);
            return CommonConst.getResult(CommonConst.RET_FAIL, "刷新失败");
        }
    }

}
